package com.edu.buservice.web.controller.index;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.edu.buservice.biz.handler.IndexHandler;
import com.edu.buservice.util.model.R;
import com.edu.buservice.web.Response.LoginResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-02-09 14:55
 **/

@Controller
@RequestMapping("/buservice")
public class IndexController {

	@Autowired
	private IndexHandler indexHandler;

	@RequestMapping("/index")
	@SaIgnore
	public String index(HttpServletRequest request, HttpServletResponse response) {

		//判断是否登录
		if(StpUtil.isLogin()){
			//已登录，跳转到首页
			return "success";
		}else{
			//未登录，跳转到登录页面
			String msg = "当前会话在SSO-Server端尚未登录，请先访问"
					+ "<a href='/login?name=sa&pwd=123456' target='_blank'> doLogin登录 </a>"
					+ "进行登录之后，刷新页面开始授权";
			return msg;
		}
	}

	/**
	* 登录接口
	*/
	@RequestMapping("/login")
	@SaIgnore
	@ResponseBody
	public R<?> login(HttpServletRequest request, HttpServletResponse response) {
		String targetUrl = indexHandler.login(request, response);

		return R.success(LoginResult.builder().accessToken(StpUtil.getTokenValue()).redirect(targetUrl).build());


	}

	/**
	* 登出接口
	*/
	@RequestMapping("/logout")
	@ResponseBody
	public R<?> logout(HttpServletRequest request, HttpServletResponse response) {

		StpUtil.logout();

		return R.success(true);

	}

}
